package pl.edu.pw.polygen;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import pl.edu.pw.polygen.security.User;
import pl.edu.pw.polygen.util.ApplicationHolder;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.HttpServletRequestListener;

@Component
@Scope("prototype")
public class PolygenApplication extends Application implements HttpServletRequestListener {

	private final static Logger LOG = Logger.getLogger(PolygenApplication.class);
	
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private MainWindow mainWindow;
	
	public PolygenApplication(){
		super();
	}
	
	@Override
    public void init(){
		User loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		setUser(loggedUser);
		setMainWindow(mainWindow);
		initApp();
		LOG.info("Application started");
    }
	
	private void initApp(){
		mainWindow.loadProjects();
	}
	
	

	@Override
	public void onRequestStart(HttpServletRequest request,
			HttpServletResponse response) {
		if (LOG.isTraceEnabled()) {
			LOG.trace("onRequestStart()");
		}
		ApplicationHolder.setApplication(this);
		requestStart(request, response);
	}



	@Override
	public void onRequestEnd(HttpServletRequest request,
			HttpServletResponse response) {
		if (LOG.isTraceEnabled()) {
			LOG.trace("onRequestEnd()");
		}
		try {
			requestEnd(request, response);
		} finally {
			ApplicationHolder.resetApplication();
		}
	}
	
	public void requestEnd(HttpServletRequest request, HttpServletResponse response) {
	}

	public void requestStart(HttpServletRequest request, HttpServletResponse response) {
	}
	
}
